const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const app = express()

app.use(bodyParser.json())

app.use(cors(
    {
        origin: 'http://localhost:5173',
        methods: ['GET', 'POST'],
        allowedHeaders: ['Content-Type']
    }
))


const mysql = require('mysql')

const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '199510',
  database: 'hzf_test1'
})

db.connect(err => {
  if (err) {
    console.error('数据库连接失败:', err)
    return
  }
  console.log('数据库连接成功')
})

app.post('/api/logs', (req, res) => {
  const { timestamp, level, message } = req.body
  const sql = 'INSERT INTO logs (timestamp, level, message) VALUES (?, ?, ?)'
  db.query(sql, [timestamp, level, message], (err, result) => {
    if (err) {
      console.error('日志记录失败:', err)
      res.status(500).send('日志记录失败')
      return
    }
    console.log('日志插入成功:', { timestamp, level, message })
    res.status(200).send('日志插入成功')
  })
})

app.listen(3000, () => {
  console.log('服务器已启动，监听端口 3000')
})
